var express = require('express');
var router = express.Router();
const moment = require('moment');
const crypto = require('crypto');
const config = require('../config').wechat;
var getOpenid = require('../wechat/wechat.js');
var createUnifiedOrder = require('../wechat/createUnifiedOrder.js');
var parseXMLAsync = require('../wechat/parseXMLAsync.js');
var formatMessage = require('../wechat/formatMessage.js');
var order = require('../wechat/order.js');
var addSalse = require('../wechat/addSalse.js');

moment.locale('zh-cn');

//获取推荐
router.post('/',async function(req, res, next) {

    let content = req.body

    let code = content.code;
    let string = await getOpenid(code);
    let str = JSON.parse(string)
    let openid = str.openid

    if (!content.name || !content.phone || !content.preAddress || !content.detailAddress || !content.totalMoney) {
        res.json({
            status:"1",
            msg:"缺少必要参数"
        })
    }
    await addSalse(content.goodsId)//销量增加


    // let ipReal = req.headers['x-forwarded-for'] ||
    //     req.connection.remoteAddress ||
    //     req.socket.remoteAddress ||
    //     req.connection.socket.remoteAddress
    // ipReal = ipReal.substring(7,40)
    let ipReal = req.ip.substring(7,40);

    let time_start = moment().format('YYYYMMDDHHmmss')
    let time_expire = moment().add(1, 'h').format('YYYYMMDDHHmmss')
    let out_trade_no = moment().format('YYYYMMDDHHmmss') + Math.random().toString().substr(2, 15)

    let order_sheet1 = out_trade_no.split('')
    let order_sheet = order_sheet1[3]+order_sheet1[5]+order_sheet1[7]+order_sheet1[9]+order_sheet1[11]+order_sheet1[12]+order_sheet1[13]+order_sheet1[16]+order_sheet1[18]+order_sheet1[25]

    // let wxOrder = await createUnifiedOrder(out_trade_no,'印小七高级班服定制', content.totalMoney*100, ipReal, 'JSAPI', openid, { time_start, time_expire})//将xml传给微信
    // wxOrder = await parseXMLAsync(wxOrder)//解析微信传来的xml
    // wxOrder = formatMessage(wxOrder.xml)

    ////////////////////////////////////////

    // createNonce = function () {
    //     return Math.random().toString(36).substr(2, 15) + Math.random().toString(36).substr(2, 15)
    // }
    // _sign = function (obj) {
    //     let params = []
    //     for (let key in obj) {
    //         let aLine = key + '=' + obj[key]
    //         params.push(aLine)
    //     }
    //     let strA = params.sort().join('&')
    //     let stringSignTemp = strA + `&key=${config.apiCert}`
    //     return MD5(stringSignTemp).toUpperCase()
    // }
    // function MD5(str) {
    //     let md5sum = crypto.createHash('md5')
    //     md5sum.update(str)
    //     str = md5sum.digest('hex')
    //     return str
    // }

    //////////////////////////////////////////////

    // let prepay_id = 'prepay_id=' + wxOrder.prepay_id
    // let appid = config.appID
    // let nonce_str =  createNonce()
    // let timeStamp = Math.ceil(Date.now() / 1000)+''
    // let signType = 'MD5'
    // let paySign =  _sign({ appId: appid, package: prepay_id, nonceStr: nonce_str, timeStamp, signType })//将这些信息通过签名加密
    let payOrder = content.payorder;

    for (var i = payOrder.length - 1; i >= 0; i--) {
        payOrder[i].goodsName = content.goodsName;
        payOrder[i].goodsId = content.goodsId;
        payOrder[i].swiperPic = content.swiperPic;
        payOrder[i].discPrice = content.discPrice
    }

    let tmp = {
        openid: openid,
        imgPath: content.imgPath,
        wxOrder: {},
        out_trade_no: out_trade_no,
        order_sheet: order_sheet,
        name: content.name,
        phone: content.phone,
        preAddress: content.preAddress,
        detailAddress: content.detailAddress,
        message: content.message,
        date: moment(Date.now()).format("YYYY-MM-DD HH:mm:ss"),
        tmp: payOrder,
        totalMoney: content.totalMoney
    }
    await order(tmp);
    // let opts = {
    //     appid,
    //     prepay_id,
    //     nonce_str,
    //     timeStamp,
    //     signType,
    //     paySign,
    // }

    res.json({
        status: "0",
        msg: "下单成功",
        // result: {
        //     opts: opts
        // }
    })
});


module.exports = router;